package test;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhu
 * @date 2024-03-21
 */
public class TicketRunnable implements Runnable{
    private int ticketCount = 50;
    ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public void run() {
        while (ticketCount >= 1){
            sell();
        }
    }
    private void sell(){
        try {
            reentrantLock.lock();

            if (ticketCount > 0){
                System.out.println(Thread.currentThread().getName() + "出售了第 " + ticketCount + " 张票");
                ticketCount -- ;
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }finally {
            reentrantLock.unlock();
        }
    }
}
